package vn.student.notificationforandroid;

import static vn.student.util.CommonUtilities.EMAIL;
import static vn.student.util.CommonUtilities.NAME;
import static vn.student.util.CommonUtilities.SENDER_ID;
import static vn.student.util.CommonUtilities.SERVER_URL;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gcm.GCMRegistrar;

;
public class ConfigureActivity extends Activity {

    SharedPreferences sp;
    
    EditText editName, editEmail, editUrl;
    Button btsubmit;
    SharedPreferences.Editor edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.configure_layout);
	checkNotNull(SERVER_URL, "SERVER_URL");
	checkNotNull(SENDER_ID, "SENDER_ID");
	editName = (EditText) findViewById(R.id.config_name);
	editEmail = (EditText) findViewById(R.id.config_email);
	sp = PreferenceManager.getDefaultSharedPreferences(this);
	edit = sp.edit();	
	sp = PreferenceManager.getDefaultSharedPreferences(this);
	
	if(GCMRegistrar.isRegistered(this)&&GCMRegistrar.isRegisteredOnServer(this))
	{
	    startActivity(new Intent(this, MainActivity.class));
	    //DatabaseN4S dataBase= new DatabaseN4S(this);
	    //dataBase.copyDB(DBComman.DATABASENAME, DatabaseN4S.pathDB);
	}
	
    }

    private void checkNotNull(Object reference, String name) {

	if (reference == null) {
	    throw new NullPointerException(getString(R.string.error_config,
		    name));
	}
    }

    @Override
    protected void onStop() {

	super.onStop();
	//GCMRegistrar.unregister(this);
	finish();
    }
    
    public void btSubmit(View v) {
	if(editEmail.getText().length()==0 || editName.getText().length()==0)
	{
	    Toast.makeText(this, "Điền đủ thông tin",Toast.LENGTH_SHORT).show();
	    return;
	}
	GCMRegistrar.checkDevice(this);
	GCMRegistrar.checkManifest(this);
	edit.remove(NAME);
	edit.remove(EMAIL);
	edit.putString(EMAIL, editEmail.getText().toString());
	edit.putString(NAME, editName.getText().toString());
	edit.commit();
	GCMRegistrar.register(this, SENDER_ID);
	

	if(GCMRegistrar.isRegistered(this) && GCMRegistrar.isRegisteredOnServer(this))
	{
	    startActivity(new Intent(this, MainActivity.class));
	}
	
    }
}
